package ui.swing.list;

import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class List_SelectionListener extends JFrame implements ListSelectionListener{

	private static final long serialVersionUID = -3066574079031673907L;

	JList list = null;
	JLabel label = null;
	String[] s = {"美国","日本","大陆","英国","法国","意大利","澳洲","韩国"};

	public List_SelectionListener() {
		super("List_SelectionListener");
		setSize(500, 240);
		
		label = new JLabel(" ");
		list = new JList(s);
		list.setVisibleRowCount(5);
		list.setBorder(BorderFactory.createTitledBorder("你喜欢哪个国家？"));
		list.addListSelectionListener(this);
		
		JPanel cp = new JPanel(new BorderLayout());
		cp.add(label, BorderLayout.NORTH);
		cp.add(list, BorderLayout.CENTER);
		
		setContentPane(cp);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}

	public void valueChanged(ListSelectionEvent e) {
		StringBuilder sbuilder = new StringBuilder();
		int[] indices = list.getSelectedIndices();
		for(int selIndex: indices) {
			sbuilder.append(list.getModel().getElementAt(selIndex)).append(" ,");
		}
		label.setText(sbuilder.substring(0, sbuilder.length() - 1));
	}
	
	public static void main(String[] args) {
		new List_SelectionListener();
	}
}
